/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */

import * as React from "react";
import { connect } from "react-redux";
import { IRootState, Dispatch } from "../../../../store";
import { Form, Button, Table, Modal, Input, Select } from "antd";

import { FormComponentProps } from "antd/lib/form";
import TitleCard from "src/components/TitleCard";
import moment from "moment";

const mapStateToProps = ({ user, loading }: IRootState) => ({
  user,
  loading: loading.effects.user.getUserList as any
});
const mapDispatchToProps = ({ user }: Dispatch) => ({
  getUserList: (payload: any) => user.getUserList(payload),
  getUserById: (id: any) => user.getUserById(id),
  modifyUser: (payload: any) => user.modifyUser(payload),
  saveUser: (payload: any) => user.saveUser(payload),
  findByAccountExists: (payload: any) => user.findByAccountExists(payload)
});

type connectedProps = ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

interface IState {
  visible: boolean;
  edit: boolean;
  userData: any;
  searchValue: any;
  currPage: number;
}

interface IProps extends connectedProps {
  loading: boolean;
}

class UserList extends React.Component<IProps & FormComponentProps, IState> {
  public state = {
    visible: false,
    edit: false,
    userData: "",
    searchValue: "",
    currPage: 0
  };

  public componentDidMount = () => {
    const { getUserList } = this.props;
    getUserList({
      size: 10,
      name: ""
    });
  };

  public editHandle = (id: any) => {
    console.log("editHandle");
  };

  public statusHandle = (id: any) => {
    console.log("statusHandle");
  };

  public handleOk = (e: any) => {
    const { saveUser, modifyUser } = this.props;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.id === "") {
          saveUser(values);
        } else {
          modifyUser(values);
        }

        this.setState({
          visible: false
        });
      }
    });
  };

  public handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  public showModal = async (id: any, flag: any) => {
    const { getUserById } = this.props;
    if (id !== "") {
      await getUserById(id);
    } else {
      this.props.user.userById = null;
    }
    this.setState({
      visible: true,
      edit: flag
    });
  };

  public inputChange = (e: any) => {
    this.setState({
      searchValue: e.target.value
    });
  };

  public searchHandle = () => {
    const { getUserList } = this.props;
    getUserList({
      size: 10,
      name: this.state.searchValue
    });
  };

  public changePage(pageNumber: any, pageSize: any, props: any) {
    const { getUserList } = this.props;
    const payload = {
      name: this.state.searchValue,
      page: pageNumber - 1,
      size: pageSize
    };
    this.setState({
      currPage: pageNumber
    });

    getUserList(payload);
  }

  public tableRender() {
    const { userList } = this.props.user;
    const column = [
      {
        title: "序号",
        dataIndex: "seq",
        render: (text: any, record: any, index: any) => {
          return index + 1;
        }
      },
      {
        title: "用户名",
        dataIndex: "account"
      },
      {
        title: "名称",
        dataIndex: "name"
      },
      {
        title: "状态",
        dataIndex: "status",
        render: (text: any, record: any, index: any) => {
          if (text === 0) {
            return "启用";
          } else {
            return "停用";
          }
        }
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "上次登录时间",
        dataIndex: "lastTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "管理员",
        dataIndex: "supervise",
        render: (text: any, record: any, index: any) => {
          if (text === 0) {
            return "否";
          } else {
            return "是";
          }
        }
      },
      {
        title: "操作",
        dataIndex: "",
        render: (text: any, record: any, index: any) => {
          return (
            <div>
              <Button
                type="primary"
                size="small"
                style={{ marginRight: "10px" }}
                onClick={() => this.showModal(record.id, false)}
              >
                编辑
              </Button>
            </div>
          );
        }
      }
    ];

    return (
      <Table
        dataSource={userList}
        columns={column}
        rowKey={"id"}
        pagination={{
          current: this.state.currPage,
          total: this.props.user.pageTotal,
          onChange: (page, size) => this.changePage(page, size, this.props)
        }}
      />
    );
  }

  public render() {
    const { getFieldDecorator } = this.props.form;
    const { userById } = this.props.user;
    return (
      <div className="message-container" style={{ paddingTop: 32 }}>
        <div style={{ marginLeft: "20px" }}>
          <b>名称:</b>
          <Input
            style={{ width: "200px", marginLeft: "10px" }}
            onChange={(e: any) => this.inputChange(e)}
          />
          <Button
            type="primary"
            style={{ marginLeft: "10px" }}
            onClick={this.searchHandle}
          >
            查询
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: "10px" }}
            onClick={() => this.showModal("", true)}
          >
            新增用户
          </Button>
        </div>
        <TitleCard style={{ paddingTop: 32 }}>{this.tableRender()}</TitleCard>

        <Modal
          title={this.state.edit ? "新增用户" : "编辑用户"}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose={true}
          width="500px"
          okText={"确定"}
          cancelText={"取消"}
        >
          <Form>
            <Form.Item
              label={"主键ID"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("id", {
                initialValue: userById !== null ? userById.id : "",
                rules: [
                  {
                    required: false,
                    message: "请填写用户名"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"创建时间"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("createTime", {
                initialValue: userById !== null ? userById.createTime : "",
                rules: [
                  {
                    required: false,
                    message: "请填写用户名"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"修改时间"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("modifyTime", {
                initialValue: userById !== null ? userById.createTime : "",
                rules: [
                  {
                    required: false,
                    message: "请填写用户名"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"最后登录时间"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("lastTime", {
                initialValue: userById !== null ? userById.createTime : "",
                rules: [
                  {
                    required: false,
                    message: "请填写用户名"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"用户名"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
            >
              {getFieldDecorator("account", {
                initialValue: userById !== null ? userById.account : "",
                rules: [
                  {
                    required: true,
                    message: "请填写用户名"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"名称"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
            >
              {getFieldDecorator("name", {
                initialValue: userById !== null ? userById.name : "",
                rules: [
                  {
                    required: true,
                    message: "请填写名称"
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item
              label={"密码"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
            >
              {getFieldDecorator("password", {
                initialValue: userById !== null ? userById.password : "",
                rules: [
                  {
                    required: true,
                    message: "请填写密码"
                  }
                ]
              })(<Input.Password visibilityToggle={false} />)}
            </Form.Item>
            <Form.Item
              label={"状态"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
            >
              {getFieldDecorator("status", {
                initialValue: userById !== null ? String(userById.status) : "0",
                rules: [
                  {
                    required: true,
                    message: "请选择状态"
                  }
                ]
              })(
                <Select>
                  <Select.Option key="0">启用</Select.Option>
                  <Select.Option key="1">停用</Select.Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item
              label={"管理员"}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
            >
              {getFieldDecorator("supervise", {
                initialValue:
                  userById !== null ? String(userById.supervise) : "0",
                rules: [
                  {
                    required: true,
                    message: "请选择"
                  }
                ]
              })(
                <Select>
                  <Select.Option key="0">否</Select.Option>
                  <Select.Option key="1">是</Select.Option>
                </Select>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create<IProps & FormComponentProps>({})(UserList));
